<template>
  <div class="reports-container">
    <el-card class="reports-card">
      <template #header>
        <div class="card-header">
          <span>绩效报表分析</span>
          <div class="header-actions" style="width: 900px;">

            <el-select
              v-model="selectedAssessment"
              placeholder="选择考核方案"
              clearable
              @change="handleAssessmentChange"
              style="width: 400px"
            >
              <el-option
                v-for="assessment in assessmentOptions"
                :key="assessment.id"
                :label="assessment.name"
                :value="assessment.id"
              />
            </el-select>
          </div>
        </div>
      </template>

      <el-tabs v-model="activeTab" @tab-click="handleTabChange">

        <el-tab-pane label="绩效填写情况" name="fill">
          <div class="chart-container">
            <div class="chart-wrapper">
              <div ref="gradeDistributionChart" class="chart" />
            </div>
          </div>
        </el-tab-pane>

        <el-tab-pane label="绩效指标情况" name="kpi">
          <div class="chart-container">
            <div class="chart-wrapper">
              <div ref="kpiAchievementChart" class="chart" />
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="部门绩效情况" name="department">
          <div class="chart-container">
            <div class="chart-wrapper">
              <div ref="departmentComparisonChart" class="chart" />
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { getDepartmentList } from '@/api/departments'
import { getAssessmentList } from '@/api/assessments'
import { getReportStatus, getKpiScore } from '@/api/report'
import { countFillStatusByDepartment } from '@/api/assessment-fill'

// 图表实例引用
const personalTrendChart = ref<HTMLElement>()
const departmentComparisonChart = ref<HTMLElement>()
const gradeDistributionChart = ref<HTMLElement>()
const kpiAchievementChart = ref<HTMLElement>()

// 状态变量
const activeTab = ref('fill')
const selectedDepartment = ref<number>()
const selectedAssessment = ref<number>()
const loading = ref(false)

interface Department {
  id: number
  name: string
  children?: Department[]
}

// 部门选项
const departmentOptions = ref<Department[]>([])

// 考核方案选项
const assessmentOptions = ref<Array<{id: number, name: string}>>([])

const kpiStats = ref([])

// 图表配置
const personalTrendOptions = {
  title: {
    text: '个人绩效趋势分析',
    left: 'center'
  },
  tooltip: {
    trigger: 'axis'
  },
  xAxis: {
    type: 'category',
    data: ['1月', '2月', '3月', '4月', '5月', '6月']
  },
  yAxis: {
    type: 'value',
    min: 1,
    max: 20
  },
  series: [{
    name: '绩效得分',
    type: 'line',
    data: [85, 88, 82, 90, 87, 92],
    smooth: true,
    markPoint: {
      data: [
        { type: 'max', name: '最高分' },
        { type: 'min', name: '最低分' }
      ]
    },
    markLine: {
      data: [
        { type: 'average', name: '平均分' }
      ]
    }
  }]
}

const departmentComparisonOptions = {
  title: {
    text: '部门绩效对比分析',
    left: 'center'
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  legend: {
    top: '10%'
  },
  xAxis: {
    type: 'category',
    data: []
  },
  yAxis: {
    type: 'value',
    min: 60,
    max: 100
  },
  series: [
  ]
}

const gradeDistributionOptions = {
  title: {
    text: '绩效等级分布',
    left: 'center'
  },
  tooltip: {
    trigger: 'item'
  },
  legend: {
    orient: 'vertical',
    left: 'left',
    top: 'center'
  },
  series: [
    {
      name: '等级分布',
      type: 'pie',
      radius: ['50%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: '20',
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: [
        { value: 20, name: '优秀' },
        { value: 36, name: '良好' },
        { value: 32, name: '合格' },
        { value: 12, name: '待改进' }
      ]
    }
  ]
}

const kpiAchievementOptions = {
  title: {
    text: '关键指标达成分析',
    left: 'center'
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  legend: {
    top: '10%'
  },
  xAxis: {
    type: 'value',
    max: 20
  },
  yAxis: {
    type: 'category',
    data: kpiStats.value.map((item: any) => item.name)
  },
  series: [
    {
      name: '目标值',
      type: 'bar',
      data: kpiStats.value.map((item: any) => item.target)
    },
    {
      name: '实际值',
      type: 'bar',
      data: kpiStats.value.map((item: any) => item.actual)
    }
  ]
}

// 方法
function initCharts() {
  console.log('初始化所有图表')
  
  if (personalTrendChart.value) {
    const chart = echarts.init(personalTrendChart.value)
    chart.setOption(personalTrendOptions)
    chart.resize()
  }

  if (departmentComparisonChart.value) {
    console.log('初始化部门对比图表')
    const chart = echarts.init(departmentComparisonChart.value)
    chart.setOption(departmentComparisonOptions)
    chart.resize()
  }

  if (gradeDistributionChart.value) {
    const chart = echarts.init(gradeDistributionChart.value)
    chart.setOption(gradeDistributionOptions)
    chart.resize()
  }

  if (kpiAchievementChart.value) {
    const chart = echarts.init(kpiAchievementChart.value)
    chart.setOption(kpiAchievementOptions)
    chart.resize()
  }
}

function handleTabChange() {
  console.log('标签页切换，重新渲染图表')
  nextTick(() => {
    initCharts()
  })
}

async function loadReportStatusData() {
  loading.value = true
  try {
    // 调用报表状态 API 获取数据
    const response = await getReportStatus()
    
    // 根据API响应更新图表数据
    if (response) {
      // 处理新的API响应格式：状态和数量的数组
      const statusData = response
      
      // 更新绩效等级分布图表数据
      gradeDistributionOptions.series[0].data = statusData.map(item => ({
        value: item.num,
        name: getStatusName(item.status)
      }))
      
      // 重新渲染等级分布图表
      nextTick(() => {
        if (gradeDistributionChart.value) {
          const chart = echarts.init(gradeDistributionChart.value)
          chart.setOption(gradeDistributionOptions)
        }
      })
    }
  } catch (error) {
    console.error('获取报表数据失败:', error)
    ElMessage.error('获取报表数据失败')
  } finally {
    loading.value = false
  }
}

function getProgressStatus(rate: number) {
  if (rate >= 100) return 'success'
  if (rate >= 90) return ''
  if (rate >= 80) return 'warning'
  return 'exception'
}

// 将状态代码转换为中文名称
function getStatusName(status: string): string {
  const statusMap: Record<string, string> = {
    'draft': '草稿',
    'in_progress': '进行中',
    'completed': '已完成',
    'excellent': '优秀',
    'good': '良好',
    'pass': '合格',
    'improve': '待改进'
  }
  return statusMap[status] || status
}

// 加载部门数据
async function loadDepartments() {
  try {
    const response = await getDepartmentList()
    departmentOptions.value = response
  } catch (error) {
    console.error('获取部门列表失败:', error)
    ElMessage.error('获取部门列表失败')
  }
}

// 将平铺的部门数据转换为树形结构
function buildDepartmentTree(departments: any[]): any[] {
  const departmentMap = new Map()
  const tree: any[] = []
  
  // 首先将所有部门存入map
  departments.forEach(dept => {
    departmentMap.set(dept.id, { ...dept, children: [] })
  })
  
  // 构建树形结构
  departments.forEach(dept => {
    const node = departmentMap.get(dept.id)
    if (dept.parentId) {
      const parent = departmentMap.get(dept.parentId)
      if (parent) {
        parent.children.push(node)
      }
    } else {
      tree.push(node)
    }
  })
  
  return tree
}

// 加载考核方案数据
async function loadAssessments() {
  console.log('selectedDepartment', selectedDepartment)
  try {
    const response = await getAssessmentList({
      department: selectedDepartment.value
    })
    assessmentOptions.value = response.map(assessment => ({
      id: assessment.id,
      name: assessment.name
    }))
  } catch (error) {
    console.error('获取考核方案列表失败:', error)
    ElMessage.error('获取考核方案列表失败')
  }
}

async function loadKpiScore() {
  try {
    loading.value = true
    const response = await getKpiScore()
    
    if (response) {
      // 更新KPI统计数据
      kpiStats.value = response.map((item: any) => ({
        name: item.kpiName,
        target: item.targetValue,
        actual: item.actualValue,
        achievementRate: Math.round((item.actualValue / item.targetValue) * 100)
      }))
      
      // 更新KPI达成分析图表
      kpiAchievementOptions.series[0].data = response.map((item: any) => item.kpiScore)
      kpiAchievementOptions.series[1].data = response.map((item: any) => item.managerScore)
      kpiAchievementOptions.yAxis.data = response.map((item: any) => item.kpiName)
      
      // 重新渲染图表
      if (kpiAchievementChart.value) {
        const chart = echarts.init(kpiAchievementChart.value)
        chart.setOption(kpiAchievementOptions)
      }
    }
  } catch (error) {
    console.error('获取KPI指标数据失败:', error)
    ElMessage.error('获取KPI指标数据失败')
  } finally {
    loading.value = false
  }
}



// 考核方案变化处理函数
async function handleAssessmentChange(assessmentId: number) {
  console.log('考核方案变化:', assessmentId)
  
  if (!assessmentId) {
    ElMessage.warning('请先选择考核方案')
    return
  }
  
  try {
    loading.value = true
    const response = await countFillStatusByDepartment(assessmentId)
    console.log('部门填写状态统计:', response)
    
    // 检查响应数据
    if (!response) {
      ElMessage.info('暂无数据')
      return
    }
    
    // 更新部门对比图表数据
    if (response && response.length > 0) {
      console.log('开始更新部门对比图表，数据：', response)
      
      // 获取部门名称
      const departmentNames = response.map((item: any) => {
        const dept = departmentOptions.value.find(dept => dept.id === item.departmentId)
        return dept ? dept.name : `部门${item.departmentId}`
      })
      
      console.log('部门名称：', departmentNames)
      
      // 已完成数据
      const completedData = response.map((item: any) => item.fillStatusCompleted || 0)
      const notStartedData = response.map((item: any) => item.fillStatusNotStarted || 0)
      
      console.log('已完成数据：', completedData)
      console.log('未开始数据：', notStartedData)
      
      // 更新部门对比图表
      departmentComparisonOptions.xAxis = {
        type: 'category',
        data: departmentNames
      }
      
      departmentComparisonOptions.yAxis = {
        type: 'value'
      }
      
      departmentComparisonOptions.series = [
        {
          name: '已完成',
          type: 'bar',
          data: completedData,
          itemStyle: {
            color: '#67C23A'
          }
        },
        {
          name: '未开始',
          type: 'bar',
          data: notStartedData,
          itemStyle: {
            color: '#909399'
          }
        }
      ]
      
      console.log('更新后的图表配置：', departmentComparisonOptions)
      
      // 重新渲染部门对比图表
        nextTick(() => {
          console.log('nextTick执行，检查图表元素:', departmentComparisonChart.value)
          if (departmentComparisonChart.value) {
            console.log('图表元素存在，开始初始化')
            const chart = echarts.init(departmentComparisonChart.value)
            console.log('图表初始化完成，设置选项:', departmentComparisonOptions)
            chart.setOption(departmentComparisonOptions, true)
            chart.resize()
            console.log('部门对比图表重新渲染完成')
          } else {
            console.log('图表元素不存在，延迟重试')
            setTimeout(() => {
              if (departmentComparisonChart.value) {
                const chart = echarts.init(departmentComparisonChart.value)
                chart.setOption(departmentComparisonOptions, true)
                chart.resize()
                console.log('部门对比图表延迟渲染完成')
              }
            }, 500)
          }
        })
    }
    
  } catch (error) {
    console.error('获取部门填写状态失败:', error)
    ElMessage.error('获取部门填写状态失败')
    
    // 出错时清空图表数据
    gradeDistributionOptions.series[0].data = []
    if (gradeDistributionChart.value) {
      const chart = echarts.init(gradeDistributionChart.value)
      chart.setOption(gradeDistributionOptions)
    }
    
    // 出错时也清空部门对比图表
    departmentComparisonOptions.series = []
    if (departmentComparisonChart.value) {
      const chart = echarts.init(departmentComparisonChart.value)
      chart.setOption(departmentComparisonOptions)
    }
    
  } finally {
    loading.value = false
  }
}

// 部门选择变化处理函数
async function handleDepartmentChange(departmentId: number) {
  console.log('部门选择变化:', departmentId)
  
  // 如果有选中的考核方案，重新加载数据
  if (selectedAssessment.value) {
    await handleAssessmentChange(selectedAssessment.value)
  }
}

// 测试函数 - 手动更新部门对比图表
function testUpdateDepartmentChart() {
  console.log('测试更新部门对比图表')
  
  // 模拟数据
  const testData = [
    { departmentId: 6, fillStatusCompleted: 5, fillStatusNotStarted: 7 },
    { departmentId: 7, fillStatusCompleted: 8, fillStatusNotStarted: 3 }
  ]
  
  // 获取部门名称
  const departmentNames = testData.map((item) => {
    const dept = departmentOptions.value.find(dept => dept.id === item.departmentId)
    return dept ? dept.name : `部门${item.departmentId}`
  })
  
  // 更新图表配置
  departmentComparisonOptions.xAxis = {
    type: 'category',
    data: departmentNames
  }
  
  departmentComparisonOptions.yAxis = {
    type: 'value'
  }
  
  departmentComparisonOptions.series = [
    {
      name: '已完成',
      type: 'bar',
      data: testData.map(item => item.fillStatusCompleted),
      itemStyle: { color: '#67C23A' }
    },
    {
      name: '未开始',
      type: 'bar',
      data: testData.map(item => item.fillStatusNotStarted),
      itemStyle: { color: '#909399' }
    }
  ]
  
  console.log('测试数据配置：', departmentComparisonOptions)
  
  // 重新渲染
  nextTick(() => {
    if (departmentComparisonChart.value) {
      const chart = echarts.init(departmentComparisonChart.value)
      chart.setOption(departmentComparisonOptions, true)
      chart.resize()
      console.log('测试图表更新完成')
    }
  })
}

// 生命周期钩子
onMounted(() => {
  // 加载部门数据
  loadDepartments()

  // 加载报表状态数据
  loadReportStatusData()

  // 加载绩效指标情况
  loadKpiScore()

  // 初始化图表
  initCharts()

  // 加载考核方案数据
  loadAssessments()

  // 监听窗口大小变化，重新渲染图表
  const handleResize = () => {
    nextTick(() => {
      if (gradeDistributionChart.value) {
        const chart = echarts.init(gradeDistributionChart.value)
        chart.setOption(gradeDistributionOptions)
        chart.resize()
      }
      
      if (departmentComparisonChart.value) {
        const chart = echarts.init(departmentComparisonChart.value)
        chart.setOption(departmentComparisonOptions)
        chart.resize()
      }
      
      if (kpiAchievementChart.value) {
        const chart = echarts.init(kpiAchievementChart.value)
        chart.setOption(kpiAchievementOptions)
        chart.resize()
      }
    })
  }
  window.addEventListener('resize', handleResize)
  
  // 组件卸载时移除事件监听
  onUnmounted(() => {
    window.removeEventListener('resize', handleResize)
  })
})
</script>

<style scoped>
.reports-container {
  padding: 20px;
}

.reports-card {
  background: var(--el-bg-color);
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: right;
}

.chart-container {
  display: flex;
  gap: 20px;
  margin-top: 20px;
}

.chart-wrapper {
  flex: 1;
  min-height: 400px;
}

.chart {
  width: 100%;
  height: 400px;
  min-width: 100%;
}

.chart-info {
  width: 300px;
  flex-shrink: 0;
}

.grade-stats {
  height: 100%;
}

.grade-stats-header {
  font-weight: bold;
}

.grade-item {
  text-align: center;
  padding: 15px;
  border-radius: 4px;
  background: var(--el-fill-color-light);
  margin-bottom: 10px;
}

.grade-name {
  font-size: 16px;
  font-weight: bold;
  color: var(--el-text-color-primary);
}

.grade-count {
  font-size: 24px;
  color: var(--el-color-primary);
  margin: 10px 0;
}

.grade-rate {
  color: var(--el-text-color-secondary);
}
</style>